<?php
class Article_model extends CI_Model{
	public function __construct(){
		$this->load->database();
	}
	
	//获取单条
	public function get_article($id = FALSE){
	
		if($id === FALSE){
			$query = $this->db->get("article");
			return $query->result_array();
		}
		$query = $this->db->get_where('article',array('id'=>$id));
		return $query->row_array();
	}

	//添加
	public function set_article(){
		$this->load->helper("url");
	
  
	  $data = array(
	    'title' => $this->input->post('title'),
	  	'category_id' => $this->input->post('category_id'),
		'status' => $this->input->post('status'),
	    'text' => $this->input->post('text')
	  );
	  
	  //相关分类数据变更 
	  if($result = $this->db->insert('article', $data)){
		$this->db->set('posts_count','posts_count+1',FALSE);//计算应该取消转义
		$this->db->where("FIND_IN_SET(category_id,'$data[category_id]') and 1=1");
		$this->db->update('category');
	  }
	  return $result;
	}
	
	//更新
	public function up_article($where = array(),$data){
		
		$this->db->update('article',$data,$where);
		if($this->db->affected_rows() == 1){
			return true;
		}else{
			return false;
		}
	}
	
	//更新状态
	public function up_status($id,$status){
		
		$ids = explode(',',$id['id']);
		$this->db->where_in('id',$ids);
		$this->db->update('article',$status);
		//Q: how to get the real affected_rows and the object
		//怎么获得受影响的行数以及具体行的信息
		if($this->db->affected_rows() > 0){
			return true;
		}else{
			return false;
		}
	}
	
	//删除
	public function delete($id){
		$ids = explode(',',$id);
		
		//相关分类数据变更 
		foreach($ids as $id){
			$this->db->select('category_id');
			$query = $this->db->get_where('article',array("id" => $id));
			$article = $query->row_array();
			
			$this->db->set('posts_count','IF((posts_count-1)>0,(posts_count-1),0)',FALSE);//计算应该取消转义
			$this->db->where("FIND_IN_SET(category_id,'$article[category_id]') and 1=1");
			$this->db->update('category');

		}
		
		$this->db->where_in('id',$ids);
		$this->db->delete('article');
		
		$rows = $this->db->affected_rows();
		if($rows >= 1){
			return true;
		}else{
			return false;
		}
	}
	
	//列出
	public function articleList($s=0,$l=0,$category_id = false){
	
		$this->db->limit($s,$l);
		$this->db->order_by('id','desc');
		if($cate = (int)$category_id){
			$this->db->where("category_id in('$cate')");
		}
		$rel = $this->db->get('article');
		
		return $result = $rel->result_array();
	}

	
}